package com.busionline.wotu.bannerview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.busionline.wotu.bannerview.adapter.BannerAdapter;
import com.busionline.wotu.bannerview.listener.OnBannerItemClickListener;
import com.busionline.wotu.bannerview.view.BannerViewPager;
import com.busionline.wotu.bannerview.view.DotIndicatorView;

/**
 * Created by admin on 2017/11/7.
 */

public class BannerView extends RelativeLayout {
    private static final String TAG = "BannerView";
    private BannerViewPager mBannerViewPager;
    private LinearLayout mDotContainer;
    private Context mContext;
    //小圆点选中的颜色
    private Drawable mIndicatorFocusDrawable;
    //小圆点未选中的颜色
    private Drawable mIndicatorNormalDrawable;
    //当前位置的索引 默认为0
    private int mCurrentPosition;
    private BannerAdapter mBannerAdapter;
    //描述信息
    private TextView mDescContent;
    //圆点所在的位置 默认在右边
    private int mDotGravity = 1;
    //圆点的大小 dp
    private int mDotSize = 8;
    //圆点的间距 dp
    private int mDotDistance = 2;
    //底部的颜色 默认透明
    private int mBottomColor = Color.TRANSPARENT;
    //宽度占比
    private float mWidthProperty;
    //高度占比
    private float mHeightProperty;

    public BannerView(Context context) {
        this(context, null);
    }

    public BannerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BannerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        inflate(context, R.layout.banner_view, this);
        initAttribute(attrs);
        initView();
    }

    /**
     * 初始化属性
     *
     * @param attrs
     */
    private void initAttribute(AttributeSet attrs) {
        TypedArray array = mContext.obtainStyledAttributes(attrs, R.styleable.BannerView);
        mDotGravity = array.getInt(R.styleable.BannerView_dotGravity, mDotGravity);
        mIndicatorFocusDrawable = array.getDrawable(R.styleable.BannerView_dotIndicatorFocus);
        if (mIndicatorFocusDrawable == null) {
            mIndicatorFocusDrawable = new ColorDrawable(Color.RED);
        }
        mIndicatorNormalDrawable = array.getDrawable(R.styleable.BannerView_dotIndicatorNormal);
        if (mIndicatorNormalDrawable == null) {
            mIndicatorNormalDrawable = new ColorDrawable(Color.GRAY);
        }
        mDotSize = (int) array.getDimension(R.styleable.BannerView_dotSize, dip2px(mDotSize));
        mDotDistance = (int) array.getDimension(R.styleable.BannerView_dotDistance, dip2px(mDotDistance));
        mBottomColor = array.getColor(R.styleable.BannerView_bottomColor, mBottomColor);
        mWidthProperty = array.getFloat(R.styleable.BannerView_widthProperty, mWidthProperty);
        mHeightProperty = array.getFloat(R.styleable.BannerView_heightProperty, mHeightProperty);
        array.recycle();
    }

    /**
     * 在这里设置宽高比过早（当在使用时宽高设为0，会导致在setAdapter之后也就是数据加载之后仍然为零）
     */
 /*   @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if(mWidthProperty == 0 || mWidthProperty == 0){
            return;
        }
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = (int) (mHeightProperty / mWidthProperty * width);
        Log.e(TAG, "onMeasure: height:"+height + " width:"+width  + " width2:"+getMeasuredWidth());
        setMeasuredDimension(width,height);
    }*/

    private void initView() {
        mBannerViewPager = (BannerViewPager) findViewById(R.id.bannerViewPager);
        mDescContent = (TextView) findViewById(R.id.tv_desc);
        mDotContainer = (LinearLayout) findViewById(R.id.ll_dot_container);
        RelativeLayout rl_bottom = (RelativeLayout) findViewById(R.id.rl_bottom);
        rl_bottom.setBackgroundColor(mBottomColor);
    }

    /**
     * 设置适配器
     *
     * @param bannerAdapter
     */
    public void setAdapter(BannerAdapter bannerAdapter) {
        Log.e(TAG, "setAdapter: 设置适配器");
        mBannerAdapter = bannerAdapter;
        mBannerViewPager.setAdapter(bannerAdapter);
        initDot(bannerAdapter);
        //动态设置宽高
        if(mWidthProperty == 0 || mWidthProperty == 0){
            return;
        }
        int width = getMeasuredWidth();
        int height = (int) (mHeightProperty / mWidthProperty * width);
        Log.e(TAG, "setAdapter: height:"+height + " width:"+width);
        getLayoutParams().height = height;
   /*     new Thread(new Runnable() {
            @Override
            public void run() {
                SystemClock.sleep(100);
                //动态设置宽高
                if(mWidthProperty == 0 || mWidthProperty == 0){
                    return;
                }
                int width = getMeasuredWidth();
                int height = (int) (mHeightProperty / mWidthProperty * width);
                Log.e(TAG, "setAdapter: height:"+height + " width:"+width);
                getLayoutParams().height = height;
            }
        }).start();*/
    }

    /**
     * 初始化小圆点
     *
     * @param bannerAdapter
     */
    private void initDot(BannerAdapter bannerAdapter) {
        int count = bannerAdapter.getCount();
        int gravity = Gravity.RIGHT;
        if (mDotGravity == 0) {
            gravity = Gravity.CENTER;
        } else if (mDotGravity == 1) {
            gravity = Gravity.RIGHT;
        } else if (mDotGravity == -1) {
            gravity = Gravity.LEFT;
        }
        mDotContainer.setGravity(gravity);
        for (int i = 0; i < count; i++) {
            // 不断的往点的指示器添加圆点
            DotIndicatorView indicatorView = new DotIndicatorView(mContext);
            // 设置大小
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(mDotSize, mDotSize);
            // 设置左右间距
            params.leftMargin = params.rightMargin = dip2px(mDotDistance);
            indicatorView.setLayoutParams(params);
            if (i == 0) {
                // 选中位置
                indicatorView.setDrawable(mIndicatorFocusDrawable);
            } else {
                // 未选中的
                indicatorView.setDrawable(mIndicatorNormalDrawable);
            }
            mDotContainer.addView(indicatorView);
        }
        //监听viewpager变化
        mBannerViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                pageSelcet(position);
                mCurrentPosition = position % (mBannerAdapter.getCount());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        //默认显示第一页的描述信息
        String bannerDesc = mBannerAdapter.getBannerDesc(0);
        if (!TextUtils.isEmpty(bannerDesc)) {
            mDescContent.setText(bannerDesc);
        } else {
            mDescContent.setText("");
        }
    }

    /**
     * 页面切换回调
     *
     * @param position
     */
    private void pageSelcet(int position) {
        DotIndicatorView dotIndicatorView = (DotIndicatorView) mDotContainer.getChildAt(mCurrentPosition);
        //之前亮着的点置灰
        dotIndicatorView.setDrawable(mIndicatorNormalDrawable);
        //把当前的点点亮
        int currentPosition = position % (mBannerAdapter.getCount());
        DotIndicatorView currentDotIndicatorView = (DotIndicatorView) mDotContainer.getChildAt(currentPosition);
        currentDotIndicatorView.setDrawable(mIndicatorFocusDrawable);
        //填充描述信息
        String desc = mBannerAdapter.getBannerDesc(currentPosition);
        mDescContent.setText(desc);
//        Log.e(TAG, "pageSelcet: "+position );
    }

    /**
     * dp转px
     *
     * @param dip
     * @return
     */
    private int dip2px(int dip) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dip, getResources().getDisplayMetrics());
    }


    /**
     * 开始滚动
     */
    public void startRoll() {
        mBannerViewPager.startRoll();
    }

    /**
     * 条目点击事件
     * @param bannerItemClick
     */
    public void setOnBannerItemClick(OnBannerItemClickListener bannerItemClick) {
        mBannerViewPager.setBannerListener(bannerItemClick);
    }

}
